package com.offcn.service.impl;

import com.offcn.dao.BlogMapper;
import com.offcn.dao.BtypeMapper;
import com.offcn.pojo.Blog;
import com.offcn.pojo.BlogExample;
import com.offcn.pojo.Btype;
import com.offcn.pojo.BtypeExample;
import com.offcn.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private BtypeMapper btypeMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public List<Btype> queryList(Integer pid) {
        BtypeExample example = new BtypeExample();
        BtypeExample.Criteria criteria = example.createCriteria();
        if(pid != null){
            //查小类
            criteria.andTypePidEqualTo(pid);
        }else{
            criteria.andTypePidIsNull();
        }
        List<Btype> list = btypeMapper.selectByExample(example);
        for(Btype btype : list){
            Integer id = btype.getTypeid();
            BtypeExample example1 = new BtypeExample();
            BtypeExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andTypePidEqualTo(id);

            List<Btype> child = btypeMapper.selectByExample(example1);

            btype.setChild(child);
        }
        return list;
    }

    //添加操作
    @Override
    public void add(Btype btype) {
        btypeMapper.insertSelective(btype);
    }

    //主键查询
    @Override
    public Btype queryById(int id) {
        return btypeMapper.selectByPrimaryKey(id);
    }

    //主键修改
    @Override
    public void update(Btype btype) {
        btypeMapper.updateByPrimaryKeySelective(btype);
    }

    @Override
    @Transactional
    public void delete(int id) {
        //当前类是否被博客使用，如果当前类被博客使用，那么在删除当前类时，修改博客所属的类型为暂无分类-比如0
        BlogExample example = new BlogExample();
        BlogExample.Criteria criteria = example.createCriteria();
        criteria.andTypeFkEqualTo(id);
        List<Blog> blogs = blogMapper.selectByExample(example);
        if(blogs != null && blogs.size() > 0){
            for(Blog blog : blogs){
                blog.setTypeFk(0);

                blogMapper.updateByPrimaryKeySelective(blog);
            }
        }
        //当前类如果有子类，那么把子类删除，再删除当前类
        BtypeExample btypeExample = new BtypeExample();
        BtypeExample.Criteria btypeExampleCriteria = btypeExample.createCriteria();
        btypeExampleCriteria.andTypePidEqualTo(id);
        btypeMapper.deleteByExample(btypeExample);

        btypeMapper.deleteByPrimaryKey(id);
    }
}
